1   /*
2    * Copyright (C) 2008 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.testing;
18  
19  import com.google.common.annotations.Beta;
20  
21  import java.util.ArrayList;
22  import java.util.Collections;
23  import java.util.List;
24  import java.util.logging.Handler;
25  import java.util.logging.LogRecord;
26  
27  import javax.annotation.Nullable;
28  
29  /**
30   * Tests may use this to intercept messages that are logged by the code under
31   * test.  Example:
32   * <pre>
33   *   TestLogHandler handler;
34   *
35   *   protected void setUp() throws Exception {
36   *     super.setUp();
37   *     handler = new TestLogHandler();
38   *     SomeClass.logger.addHandler(handler);
39   *     addTearDown(new TearDown() {
40   *       public void tearDown() throws Exception {
41   *         SomeClass.logger.removeHandler(handler);
42   *       }
43   *     });
44   *   }
45   *
46   *   public void test() {
47   *     SomeClass.foo();
48   *     LogRecord firstRecord = handler.getStoredLogRecords().get(0);
49   *     assertEquals("some message", firstRecord.getMessage());
50   *   }
51   * </pre>
52   *
53   * @author Kevin Bourrillion
54   * @since 10.0
55   */
56  @Beta
57  public class TestLogHandler extends Handler {
58    /** We will keep a private list of all logged records */
59    private final List<LogRecord> list =
60        Collections.synchronizedList(new ArrayList<LogRecord>());
61  
62    /**
63     * Adds the most recently logged record to our list.
64     */
65    @Override
66    public void publish(@Nullable LogRecord record) {
67      list.add(record);
68    }
69  
70    @Override
71    public void flush() {}
72  
73    @Override
74    public void close() {}
75  
76    public void clear() {
77      list.clear();
78    }
79  
80    /**
81     * Fetch the list of logged records
82     * @return unmodifiable LogRecord list of all logged records
83     */
84    public List<LogRecord> getStoredLogRecords() {
85      List<LogRecord> result = new ArrayList<LogRecord>(list);
86      return Collections.unmodifiableList(result);
87    }
88  }